#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include <Update.h>

AsyncWebServer server(80);

const int ledPin = 2; // 小灯连接的GPIO引脚

void Server_Init() {
  pinMode(ledPin, OUTPUT); // 初始化小灯引脚为输出模式

  // 挂载SPIFFS
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  // 处理根目录的访问
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", "text/html");
  });

  // 处理小灯开关的路由
  server.on("/toggle-led", HTTP_GET, [](AsyncWebServerRequest *request){
    digitalWrite(ledPin, !digitalRead(ledPin)); // 切换小灯状态
    request->send(200, "text/plain", digitalRead(ledPin) ? "LED on" : "LED off");
  });

  // 处理OTA更新的路由
  server.on("/update-firmware", HTTP_POST, [](AsyncWebServerRequest *request){
    // 更新成功或失败后的响应
    AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
    response->addHeader("Connection", "close");
    request->send(response);
    ESP.restart();
  }, [](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){
    // 上传过程中的处理
    if (!index){
      Serial.printf("Update Start: %s\n", filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { // 如果不能开始更新，则返回
        Update.printError(Serial);
      }
    }
    if (!Update.hasError()) {
      if (Update.write(data, len) != len) { // 写入数据
        Update.printError(Serial);
      }
    }
    if (final) { // 如果完成了更新
      if (Update.end(true)) { // 如果更新成功
        Serial.printf("Update Success: %uB\n", index + len);
      } else {
        Update.printError(Serial);
      }
    }
  });

  // 启动服务器
  server.begin();
}
